<template>
  <div class="app-container">
    <el-row>
      <el-col :span="24">
        <el-button type="primary" size="small" @click="handleAdd">新增轮播</el-button>
      </el-col>
    </el-row>
    <BaseTable :table-columns="tableColumns" :table-data="tableData" :options="tableOptions" :total="pages.total"
      v-model:page-num="pages.pageNum" v-model:page-size="pages.pageSize" @turnOn="search" :tableLoading="tableLoading">
      <template v-slot:isShow="{ row }">
        <el-tag type="success" v-if="row.isShow == 1">{{ row.isShow == 1 ? '是' : '否' }}</el-tag>
        <el-tag type="danger" v-else>{{ row.isShow == 1 ? '是' : '否' }}</el-tag>
      </template>
      <template v-slot:operation="{ row }">
        <el-button type="primary" text @click="handleTableItemEdit(row)">编辑</el-button>
        <el-button type="danger" text @click="handleTableItemDel(row)">删除</el-button>
      </template>
      <template v-slot:url="{ row }">
        <el-image :src="row.url" :preview-src-list="[row.url]" :preview-teleported="true"></el-image>
      </template>
      <template v-slot:linkType="{ row }">
        {{ mapKeyLabel(row.linkType, linkTypeList) }}
      </template>
    </BaseTable>
    <Dialog ref="dialogRef" :title="dialogOptions.title" :width="dialogOptions.width" @confirm="handleDialogConfirm">
      <template v-slot:content>
        <el-form :model="diaFormData" ref="diaFormDataRef" label-width="70px" label-position="left">
          <el-form-item label="名称" prop="name">
            <el-input v-model="diaFormData.name" placeholder="名称"></el-input>
          </el-form-item>
          <el-form-item label="描述" prop="desc">
            <el-input v-model="diaFormData.desc" placeholder="描述" type="textarea" show-word-limit
              :maxlength="100"></el-input>
          </el-form-item>
          <el-form-item label="图片" prop="url">
            <ImageSelector v-model:imgUrl="diaFormData.url" type="img"></ImageSelector>
          </el-form-item>
          <el-form-item label="跳转类型" prop="linkType">
            <el-select v-model="diaFormData.linkType" placeholder="请选择跳转类型" @change="changedLinkType($event,'1')">
              <el-option v-for="item in linkTypeList" :key="item.value" :label="item.label"
                :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="页面" prop="toLink" v-show="diaFormData.linkType === '1'">
            <el-select v-model="diaFormData.toLink" placeholder="请选择页面" clearable @change="changedTolink">
              <el-option v-for="item in pagesList" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="动态" prop="toLink" v-show="diaFormData.linkType === '2'">
            <el-select v-model="diaFormData.toLink" placeholder="请选择动态" clearable style="width: 100%;" @change="changedTolink">
              <el-option v-for="item in newsList" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="产品" prop="toLink" v-show="diaFormData.linkType === '3'">
            <el-select v-model="diaFormData.toLink" placeholder="请选择产品" clearable style="width: 100%;" @change="changedTolink">
              <el-option v-for="item in prodList" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="排序" prop="order">
            <el-input v-model="diaFormData.order" type="number" placeholder="排序" :min="0"></el-input>
          </el-form-item>
          <el-form-item label="是否展示" prop="isShow">
            <el-switch v-model="diaFormData.isShow" inline-prompt active-text="是" inactive-text="否" :active-value="1"
              :inactive-value="0" />
          </el-form-item>
        </el-form>
      </template>
    </Dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, nextTick } from 'vue'
import useHooksTable from './useHooksTable'
import useHooksDialog from './useHooksDialog'
import BaseTable from '@/components/BaseTable/index.vue'
import Dialog from '@/components/Dialog/index.vue'
import { resetForm, mapKeyLabel } from '@/utils/tools'
import { FormInstance } from 'element-plus'
import { queryConfiguration, createConfiguration, updateConfiguration, deleteConfiguration } from '@/api/home'
import { getProjDropdownList } from '@/api/content/project'
import ImageSelector from '@/components/ImageSelector/index.vue'
import FSMessage from '@/utils/message'
import { cloneDeep } from 'lodash-es'
// ------- variable -------
const { tableColumns, tableData, tableOptions, linkTypeList, pagesList, prodList, newsList } = useHooksTable()
const { dialogOptions } = useHooksDialog()
const formData = ref({
  name: ''
})
const pages = ref({
  pageSize: 20,
  pageNum: 1,
  total: 0
})
const dialogRef = ref(null)
const tableLoading = ref<boolean>(false)
const diaFormDataRef = ref<FormInstance>(null)
const diaFormData = ref({
  name: '',
  desc: '',
  url: '',
  toLink: '',
  order: '',
  isShow: 0,
  linkType: '',
  toLinkDetail: ''
})

// ------- function -------
const search = async () => {
  try {
    tableLoading.value = true
    const res = await queryConfiguration({ ...pages.value, ...formData.value })
    tableLoading.value = false
    res.data.rows.forEach((item, index) => {
      // @ts-ignore
      item.index = index + 1 + (pages.value.pageNum - 1) * pages.value.pageSize
    })
    tableData.value = res.data.rows
    pages.value.total = res.data.total
  } catch (error) {
    console.log(error)
    tableLoading.value = true
  }
}

const handleTableItemEdit = async (row) => {
  diaFormData.value = cloneDeep(row)
  await changedLinkType(row.linkType, '2')
  // @ts-ignore
  delete diaFormData.value.index
  dialogOptions.value.openType = 2
  dialogRef.value.visiableDialog()
}

const handleTableItemDel = async (row) => {
  try {
    FSMessage.confirm('是否确认删除', '警告').then(async () => {
      await deleteConfiguration({ id: row._id })
      search()
      dialogRef.value.invisiableDialog()
      FSMessage.success('删除成功')
    })
  } catch (error) {
    console.log(error)
  }
}

const handleAdd = () => {
  dialogOptions.value.openType = 1
  showDialog()
}

const resetFormData = () => {
  diaFormData.value = {
    name: '',
    url: '',
    toLink: '',
    order: '',
    isShow: 0,
    linkType: '',
    desc: '',
    toLinkDetail: ''
  }
}

const showDialog = () => {
  dialogRef.value.visiableDialog()
  resetFormData()
}

const handleDialogConfirm = async () => {
  try {
    dialogOptions.value.openType === 1 ? await createConfiguration(diaFormData.value) : await updateConfiguration(diaFormData.value)
    search()
    FSMessage.success('操作成功')
    dialogRef.value.invisiableDialog()
  } catch (error) {
    console.log(error)
  }
}

/**
 * @breif: 跳转类型改变
 * @param {*} type
 * @param {*} openType
 * @return {*} null
 */
const changedLinkType = async (type: string, openType:string) => {
  if (openType === '1') {
    diaFormData.value.toLink = '' // 清空之前的选项
  }
  if (type === '3' && !prodList.value.length) {
    const res = await getProjDropdownList()
    res.data.forEach(item => {
      prodList.value.push({
        label: item.name,
        value: '/detail/' + item._id
      })
    })
  }
}

/**
 * @breif: 跳转链接文字描述
 * @param {*} value
 * @return {*}
 */
const changedTolink = (value) => {
  const linkType = diaFormData.value.linkType
  if (linkType === '1') {
    diaFormData.value.toLinkDetail = pagesList.find(item => item.value === value)?.label
  } else if (linkType === '2') {
    diaFormData.value.toLinkDetail = newsList.value.find(item => item.value === value)?.label
  } else if (linkType === '3') {
    diaFormData.value.toLinkDetail = prodList.value.find(item => item.value === value)?.label
  }
}

const initPage = () => {
  search()
}
initPage()
</script>
<style scoped lang="scss"></style>
